package public

import (
	"bufio"
	"fmt"
	"log"
	"os"

	"github.com/chenqinghe/baidu-ai-go-sdk/voice"
)

// TextToSpeech Voice Composition
func TextToSpeech(msg string, path string) int {
	APIKEY := "qKfKR0RPVGGnxpL8BTUQ39nc"
	APISECRET := "x1Aq5is0OilkZHilTVdAvxWAUjvGo9rG"
	client := voice.NewVoiceClient(APIKEY, APISECRET)
	//msg := "　红军不怕远征难，万水千山只等闲。五岭逶迤腾细浪，乌蒙磅礴走泥丸。金沙水拍云崖暖，大渡桥横铁索寒。更喜岷山千里雪，三军过后尽开颜。"
	file, err := client.TextToSpeech(msg)
	if err != nil {
		log.Fatal(err)
		return -1
	}

	f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		log.Fatal(err)
		return -1
	}
	defer f.Close()
	if _, err := f.Write(file); err != nil {
		log.Fatal(err)
		return -1
	}
	return 0
}

//TextToVoice tools
func TextToVoice(input string, output string) int {

	msg := ToolsReadTxtMsg(input)
	if len(msg) == 0 {
		fmt.Println("txt is null")
		return -1
	}
	return TextToSpeech(msg, output)
}

//ToolsReadTxtMsg 读取文本数据
func ToolsReadTxtMsg(path string) string {
	file, err := os.Open(path)
	if err != nil {
		fmt.Println(err)
		return ""
	}
	defer file.Close()

	var buffer []string
	scanner := bufio.NewScanner(file)
	var lines string

	for scanner.Scan() {
		lines = scanner.Text()
		buffer = append(buffer, lines)

	}
	if len(buffer) == 0 {
		return ""
	}

	//字符串拼接
	var result string
	for _, data := range buffer {
		result += data
		result += "\r\n"
	}
	fmt.Println(result)
	return result

}
